package com.yaDuo.common.extra

import com.google.gson.JsonSyntaxException
import com.yaDuo.common.base.BaseApplication
import com.yaDuo.newcommon.R
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/**
 * @author YaDuo
 * time 2025-01-03 17:37
 * 这里对[Throwable]进行额外的拓展方法
 */
fun Throwable?.parseErrorString(): String = when (this) {
    is ConnectException, is SocketException -> {
        if (message?.contains("Network is unreachable") == true)
            getString(R.string.MobileNetUseless)
        if (message?.contains("Failed to connect to") == true)
            getString(R.string.FailedToConnect)
        else
            getString(R.string.ConnectException)
    }

    is HttpException -> {
        if (message?.contains("HTTP 50") == true) {
            message!!.substring(0, 8)
        } else {
            getString(R.string.HttpException)
        }
    }

    is SocketTimeoutException, is TimeoutException -> getString(R.string.SocketTimeoutException)

    is InterruptedIOException -> {
        if (message?.contains("timeout") == true)
            getString(R.string.SocketTimeoutException)
        else
            getString(R.string.ConnectException)
    }

    is UnknownHostException -> getString(R.string.UnknownHostException)

    is JsonSyntaxException -> getString(R.string.JsonSyntaxException)

    is IllegalArgumentException -> {
        if (message?.contains("baseUrl must end in ") == true)
            if (BaseApplication.get().isNetWorkActive()) getString(R.string.HostBaseUrlError)
            else getString(R.string.MobileNetUseless)
        else message ?: getString(R.string.ElseNetException)
    }

    else -> getString(R.string.ElseNetException)
}

fun getString(resID: Int): String = BaseApplication.get().getString(resID)